package com.tendory.gpssim.service.jt808;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class FrameDecoderHandler extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        Object decoded = decode(ctx, in);
        if (decoded != null) {
            out.add(decoded);
        }
    }
    private Object decode(ChannelHandlerContext ctx, ByteBuf buf) {
        if (buf.readableBytes() < 2) {
            return null;
        }

        while (buf.getUnsignedByte(buf.readerIndex()) != 0x7e) {
            buf.readByte();
        }
        if (buf.getUnsignedByte(buf.readerIndex() + 1) == 0x7e) {
            buf.readByte();
        }

        int index = buf.indexOf(buf.readerIndex() + 1, buf.writerIndex(), (byte) 0x7e);
        if (index != -1) {
            ByteBuf result = Unpooled.buffer(index + 1 - buf.readerIndex());

            while (buf.readerIndex() <= index) {
                int b = buf.readUnsignedByte();
//                if (b == 0x7d) {
//                    int ext = buf.readUnsignedByte();
//                    if (ext == 0x01) {
//                        result.writeByte(0x7d);
//                    } else if (ext == 0x02) {
//                        result.writeByte(0x7e);
//                    }
//                } else {
                result.writeByte(b);
//                }
            }
            return result;
        }
        return null;
    }
}
